
//
//  UILabel+Line.m
//  HX_GTS2
//
//  Created by Mata on 2017/12/29.
//  Copyright © 2017年 gw. All rights reserved.
//

#import "UILabel+Line.h"
#import <CoreText/CoreText.h>

@implementation UILabel (Line)
- (NSArray *)getLinesArrayOfStringInLabel{
    NSString *text = [self text];
    if (!text.length) {
        return @[@""];
    }
    CGRect rect = [self frame];
    NSRange range = NSMakeRange(0, text.length);
    NSRange *p = &range;
    NSDictionary *attrDic = [self.attributedText attributesAtIndex:0 effectiveRange:p];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttributes:attrDic range:NSMakeRange(0, text.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
        [linesArray addObject:lineString];
    }
    
    CGPathRelease(path);
    CFRelease( frame );
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}
@end
